package com.zjt.service;

import com.zjt.entity.product.Knowledge;
import com.zjt.vo.ProductDataVO;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 与物码中心数据的接口定义与实现
 * Dom4j 生成XML文档与解析XML文档
 */
@Component
public class XmlDocumentService implements IXmlDocumentService {
    private static Logger logger = LoggerFactory.getLogger(XmlDocumentService.class);
	//创建xml文件；
	//参数fileName 是文件全路径名称
	public void createXml(String fileName) {
		Document document = DocumentHelper.createDocument();
		Element employees = document.addElement("employees");//文档增加元素
		Element employee = employees.addElement("employee");
		Element name = employee.addElement("name");
		name.setText("ddvip");//元素name中的数据时“ddvip”
		Element sex = employee.addElement("sex");
		sex.setText("m");
		Element age = employee.addElement("age");
		age.setText("29");
		try {
			Writer fileWriter = new FileWriter(fileName);
			XMLWriter xmlWriter = new XMLWriter(fileWriter);
			xmlWriter.write(document);
			xmlWriter.close();
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}

	}


	public ProductDataVO getProductDataFromHttpGet(String url) throws IOException{
        ProductDataVO productDataVO = null;
        try {
			URL urladdress = new URL(url);
			SAXReader saxReader = new SAXReader();
			Document document = saxReader.read(urladdress);
			Element employees = document.getRootElement();//得到根元素
            if (employees.elementIterator("firmData")==null)
                return null;//如果没有firmData  认为物码中心无此条码数据
            productDataVO = new ProductDataVO();
            for (Iterator i = employees.elementIterator("firmData"); i.hasNext();) {
				Element club = (Element) i.next();//根元素下级的元素
				for (Iterator j = club.elementIterator(); j.hasNext();) {
					Element node = (Element) j.next();//得到一级元素的节点
                    if (node.getName().equalsIgnoreCase("firmName"))
                        productDataVO.setFirmName(node.getTextTrim());
                    else if (node.getName().equalsIgnoreCase("address"))
                            productDataVO.setAddress(node.getTextTrim()); //得到节点名称和节点数据
                    else if (node.getName().equalsIgnoreCase("extension"))
                        productDataVO.setFirmExtension(node.getTextTrim()); //得到节点名称和节点数据
				}

			}

            if (employees.elementIterator("itemData")==null)
                return productDataVO;  //如果没有itemData  认为物码中心无此条码的产品数据
			for (Iterator i = employees.elementIterator("itemData"); i.hasNext();) {
				Element club = (Element) i.next();//根元素下级的元素
				for (Iterator j = club.elementIterator(); j.hasNext();) {
					Element node = (Element) j.next();//得到一级元素的节点
					if (node.attribute("unitOfMeasure")!=null)//单位
					{
                        Element valueElement = (Element)node.elementIterator("value").next();
                        if (node.getName().equalsIgnoreCase("height"))
                            productDataVO.setHeight(valueElement.getTextTrim());
                        else if (node.getName().equalsIgnoreCase("width"))
                            productDataVO.setWidth(valueElement.getTextTrim()); //得到节点名称和节点数据
                        else if (node.getName().equalsIgnoreCase("depth"))
                            productDataVO.setDepth(valueElement.getTextTrim());
                        else if (node.getName().equalsIgnoreCase("netContent"))
                            productDataVO.setNetContent(valueElement.getTextTrim());
                        else if (node.getName().equalsIgnoreCase("grossWeight"))
                            productDataVO.setGrossWeight(valueElement.getTextTrim());
                        else if (node.getName().equalsIgnoreCase("netWeight"))
                            productDataVO.setNetWeight(valueElement.getTextTrim());
					}
					else
                    {
                        if (node.getName().equalsIgnoreCase("gtin"))
                            productDataVO.setGtin(node.getTextTrim());
                        else if (node.getName().equalsIgnoreCase("itemName"))
                            productDataVO.setItemName(node.getTextTrim());
                        else if (node.getName().equalsIgnoreCase("brandName"))
                            productDataVO.setBrandName(node.getTextTrim()); //得到节点名称和节点数据
                        else if (node.getName().equalsIgnoreCase("specification"))
                            productDataVO.setSpecification(node.getTextTrim());
                        else if (node.getName().equalsIgnoreCase("description"))
                            productDataVO.setDescription(node.getTextTrim());
                        else if (node.getName().equalsIgnoreCase("shortDescription"))
                            productDataVO.setShortDescription(node.getTextTrim());
                        else if (node.getName().equalsIgnoreCase("packagingTypeCode"))
                            productDataVO.setPackagingTypeCode(node.getTextTrim());
                        else if (node.getName().equalsIgnoreCase("packagingMaterialCode"))
                            productDataVO.setPackagingMaterialCode(node.getTextTrim());
                        else if (node.getName().equalsIgnoreCase("classCode"))
                            productDataVO.setClassCode(node.getTextTrim());
                        else if (node.getName().equalsIgnoreCase("extension"))
                            productDataVO.setExtension(node.getTextTrim());
                    }
				}
			}
			
		} catch (DocumentException e) {
			logger.error("getProductDataFromHttpGet exception "+e.getMessage()+"productDataVO="+productDataVO.toString());
		}
        logger.error("getProductDataFromHttpGet productDataVO="+productDataVO.toString());
        return productDataVO;
	}	

    @Override
    public List<Knowledge> getListFromXml(String xmlPath) throws IOException {
        List<Knowledge> list = new ArrayList<Knowledge>();
        File path = new File(xmlPath);
        try {
            if (path.exists())
            {
                SAXReader saxReader = new SAXReader();
                File[] files = path.listFiles();
                for (File file:files)
                {
                    Knowledge knowledge = new Knowledge();
                    Document document = saxReader.read(file);
                    Element employees = document.getRootElement();//得到根元素
                    if (employees.elementIterator("titleinfocontent")==null)
                        return null;//如果没有firmData  认为物码中心无此条码数据
                    for (Iterator i = employees.elementIterator("firmData"); i.hasNext();) {
                        Element club = (Element) i.next();//根元素下级的元素
                        for (Iterator j = club.elementIterator(); j.hasNext();) {
                            Element node = (Element) j.next();//得到一级元素的节点
                            //if (node.getName().equalsIgnoreCase("firmName"))
                                //productDataVO.setFirmName(node.getTextTrim());
                            //else if (node.getName().equalsIgnoreCase("address"))
                              //  productDataVO.setAddress(node.getTextTrim()); //得到节点名称和节点数据
                            //else if (node.getName().equalsIgnoreCase("extension"))
                              //  productDataVO.setFirmExtension(node.getTextTrim()); //得到节点名称和节点数据
                        list.add(knowledge);
                        }
                    }
                }
            }
        } catch (DocumentException e) {
            logger.error("getListFromXml exception "+e);
        }
        logger.error("getListFromXml exception");
        return list;
    }


    public static void main(String[] args) {
        XmlDocumentService demo = new XmlDocumentService();//6934290900686   6907260166061
        String url = "http://ws2.gs1cn.org/anccService.asmx/getProductDataByBarCode?clientId=84d10dbe-44a9-4b91-af18-46d04995b925&barcode=6907260166061";
        try
        {
            ProductDataVO vo = demo.getProductDataFromHttpGet(url);
            System.out.println(vo.toString());
        }catch(Exception e){}
    }
}
